All files / src/pages [...slug].astro

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
---
import { getCollection, render } from 'astro:content';
import Prism from 'prismjs';
import 'prismjs/components/prism-typescript';
import 'prismjs/components/prism-bash';
import 'prismjs/components/prism-json';
import 'prismjs/components/prism-yaml';
import 'prismjs/components/prism-jsx';
import 'prismjs/components/prism-tsx';
import Layout from '../layouts/Layout.astro';
import Header from '../components/Header/index.tsx';
import ShareBox from '../components/ShareBox/index.tsx';
import Sidebar from '../components/Sidebar/index.tsx';
import RelatedPosts from '../components/Relateds/index.tsx';
import TimeToRead from '../components/TimeToRead/index.tsx';
import TextToSpeech from '../components/TextToSpeech/index.tsx';
import AuthorBio from '../components/AuthorBio/index.tsx';
import Breadcrumb from '../components/Breadcrumb.astro';
import Paywall from '../components/Paywall/index.tsx';
import config from '../config/index.json';
import { parseDate } from '../utils/index';
 
export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => {
    const slug = post.slug;
    return {
      params: { slug },
      props: { post },
    };
  });
}
 
const { post } = Astro.props;
 
const isPremium = post.data.premium === true;
// For premium posts, only render the full post on premium-full page (for encryption).
// The teaser page renders only the content before <!-- paywall -->.
const { Content: PostContent } = isPremium
  ? { Content: null }
  : await render(post);
 
const rawText = post.body || '';
 
// Extract teaser markdown for premium posts (content before <!-- paywall --> marker).
// We never include the full content in the teaser page HTML.
const teaserMarkdown = isPremium ? rawText.split('<!-- paywall -->')[0].trim() : '';
 
function renderTableBlock(block: string): string {
  const lines = block.split('\n').filter((l) => l.trim().startsWith('|'));
  if (lines.length < 2) return `<p>${block.replace(/\n/g, '<br>')}</p>`;
  const rows = lines.map((l) =>
    l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim())
  );
  const isSeparator = rows[1]?.every((c) => /^[-: ]+$/.test(c));
  if (!isSeparator) return `<p>${block.replace(/\n/g, '<br>')}</p>`;
  const header = `<thead><tr>${rows[0].map((c) => `<th>${c}</th>`).join('')}</tr></thead>`;
  const body = `<tbody>${rows.slice(2).map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join('')}</tr>`).join('')}</tbody>`;
  return `<div class="table-responsive"><table class="table">${header}${body}</table></div>`;
}
 
function renderTeaserHtml(md: string): string {
  return md
    .replace(/```(?:toc|mermaid)[\s\S]*?```\n?/g, '') // strip toc/mermaid blocks (can't render in teaser)
    .replace(/^## Table of Contents\s*$/gm, '') // strip bare ToC heading left after block removal
    .replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => {
      const grammar = lang && Prism.languages[lang];
      const highlighted = grammar
        ? Prism.highlight(code.trimEnd(), grammar, lang)
        : code.trimEnd().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
      return `<pre class="language-${lang}"><code class="language-${lang}">${highlighted}</code></pre>`;
    })
    .replace(/::github\{repo="([^"]+)"\}/g, (_, repo) =>
      `<a href="https://github.com/${repo}" target="_blank" rel="noopener noreferrer" style="display:inline-flex;align-items:center;gap:6px;padding:6px 12px;border:1px solid #d7d7d7;border-radius:6px;font-size:0.875rem;color:#005b94;text-decoration:none;">` +
      `<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>` +
      `${repo}</a>`
    )
    .replace(/^### (.+)$/gm, '<h3>$1</h3>')
    .replace(/^## (.+)$/gm, '<h2>$1</h2>')
    .replace(/^# (.+)$/gm, '<h1>$1</h1>')
    .replace(/\*\*\*(.+?)\*\*\*/g, '<strong><em>$1</em></strong>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" rel="noopener noreferrer">$1</a>')
    .split('\n\n')
    .map((p) => p.trim())
    .filter(Boolean)
    .map((p) => {
      if (p.startsWith('<h') || p.startsWith('<ul') || p.startsWith('<ol') || p.startsWith('<div') || p.startsWith('<a') || p.startsWith('<pre')) return p;
      if (p.startsWith('|')) return renderTableBlock(p);
      return `<p>${p.replace(/\n/g, '<br>')}</p>`;
    })
    .join('\n');
}
const teaserHtml = isPremium ? renderTeaserHtml(teaserMarkdown) : '';
const speechText = rawText
  .replace(/## Table of Contents[\s\S]*?(?=\n## )/g, '')
  .replace(/```[\s\S]*?```/g, '')
  .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
  .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
  .replace(/`([^`]*)`/g, '$1')
  .replace(/<[^>]+>/g, '')
  .replace(/^#{1,6}\s*/gm, '')
  .replace(/[*_~>]/g, '')
  .replace(/\n{3,}/g, '\n\n')
  .trim();
const wordCount = rawText
  .replace(/```[\s\S]*?```/g, '')
  .replace(/`([^`]*)`/g, '$1')
  .replace(/[#*_\[\]()!]/g, '')
  .replace(/\s+/g, '')
  .length;
const minutes = Math.ceil(wordCount / 400);
 
const slug = post.slug;
const shareURL = `${config.siteUrl}/${slug}/`;
 
// descriptionフォールバック: frontmatterにdescriptionがない場合、記事本文の冒頭から自動生成
const fallbackDescription = rawText
  .replace(/## Table of Contents[\s\S]*?(?=\n## )/g, '')
  .replace(/```[\s\S]*?```/g, '')
  .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
  .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
  .replace(/`([^`]*)`/g, '$1')
  .replace(/<[^>]+>/g, '')
  .replace(/^#{1,6}\s*/gm, '')
  .replace(/[*_~>|]/g, '')
  .replace(/\n+/g, ' ')
  .trim()
  .slice(0, 120);
const postDescription = post.data.description || `${fallbackDescription}...`;
 
const allPosts = await getCollection('blog');
const sorted = allPosts.sort(
  (a, b) => new Date(b.data.date).getTime() - new Date(a.data.date).getTime()
);
 
const latestPosts = sorted.slice(0, 6).map((p) => ({
  title: p.data.title,
  slug: p.slug,
  date: p.data.date.toISOString(),
  url: p.slug,
}));
 
const allPostsForSidebar = sorted.map((p) => ({
  date: p.data.date.toISOString(),
  tags: p.data.tags || [],
}));
 
const allPostsForRelated = sorted.map((p) => ({
  title: p.data.title,
  tags: p.data.tags || [],
  date: p.data.date.toISOString(),
  headerImage: p.data.headerImage,
  slug: `/${p.slug}/`,
}));
 
// Markdownコピー用: YAML frontmatter + body を構築
function yamlQuote(value: string): string {
  if (/[:#[{}&*!|>'"%@`,\n\]]/.test(value) || value.startsWith(' ') || value.endsWith(' ')) {
    return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
  }
  return value;
}
const mdLines: string[] = ['---'];
mdLines.push(`title: ${yamlQuote(post.data.title)}`);
mdLines.push(`date: ${post.data.date.toISOString()}`);
if (post.data.description) {
  mdLines.push(`description: ${yamlQuote(post.data.description)}`);
}
if (post.data.tags && post.data.tags.length > 0) {
  mdLines.push('tags:');
  for (const tag of post.data.tags) {
    mdLines.push(`  - ${tag}`);
  }
}
if (post.data.headerImage) {
  mdLines.push(`headerImage: ${yamlQuote(post.data.headerImage)}`);
}
mdLines.push(`url: ${shareURL}`);
mdLines.push(`author: ${config.author}`);
mdLines.push('---');
const rawMarkdown = mdLines.join('\n') + '\n\n' + rawText;
---
 
<Layout
  title={post.data.title}
  description={postDescription}
  ogImage={post.data.headerImage || config.defaultImage}
  ogpPath={`/og/${slug}.png`}
  isPostPage={true}
  isPost={true}
  tag={post.data.tags?.[0] || ''}
  canonicalUrl={shareURL}
  datePublished={post.data.date.toISOString()}
  dateModified={(post.data.updatedDate || post.data.date).toISOString()}
  keywords={post.data.tags || []}
  faq={post.data.faq || []}
  noindex={post.data.noindex}
  wordCount={wordCount}
>
  <div class="post row order-2">
    <Header
      client:idle
      img={post.data.headerImage || config.defaultImage}
      title={post.data.title}
      authorName={config.author}
      authorImage={true}
      subTitle={parseDate(post.data.date.toISOString())}
      showCopyMd={true}
    />
    <Sidebar
      client:visible
      latestPosts={latestPosts}
      allPosts={allPostsForSidebar}
      totalCount={sorted.length}
    />
    <main class="col-xl-7 col-lg-6 col-md-12 col-sm-12 order-2">
      <Breadcrumb tag={post.data.tags?.[0] || ''} title={post.data.title} />
      <TimeToRead client:idle words={wordCount} minutes={minutes} />
      <TextToSpeech client:idle text={speechText} />
      {post.data.useAi && (
        <aside style="background:#fffbe6; border-left:4px solid #f0c040; padding:12px; margin-bottom:16px; border-radius:4px;">
          <p>この記事は筆者(<a href="https://portfolio.tubone-project24.xyz/" target="_blank" rel="noopener noreferrer" style="color:#0a58ca; text-decoration:underline;">tubone</a>)が<a href="https://github.com/tubone24/whisper-realtime" target="_blank" rel="noopener noreferrer" style="color:#0a58ca; text-decoration:underline;">whisper-realtime</a>を利用し文字起こしした内容をもとにAIにて記事の執筆を実施したものです。</p>
        </aside>
      )}
      <div class="content-white-inner">
        {isPremium ? (
          <Fragment>
            <div set:html={teaserHtml} />
            <Paywall
              client:load
              slug={slug}
              priceUsd={post.data.priceUsd ?? 0.05}
            />
          </Fragment>
        ) : (
          PostContent && <PostContent />
        )}
      </div>
      <div class="content-white-inner">
        <h2>tubone24にラーメンを食べさせよう!</h2>
        <p>ぽちっとな↓</p>
        <a href="https://www.buymeacoffee.com/tubone24">
          <img
            src="https://img.buymeacoffee.com/button-api/?text=Buy me a ramen&emoji=🍜&slug=tubone24&button_colour=40DCA5&font_colour=ffffff&font_family=Lato&outline_colour=000000&coffee_colour=FFDD00"
            alt="Buy me a ramen"
            width="217"
            height="60"
            loading="lazy"
            decoding="async"
          />
        </a>
      </div>
      <AuthorBio client:idle />
      <RelatedPosts
        client:idle
        title={post.data.title}
        tags={post.data.tags || []}
        allPosts={allPostsForRelated}
      />
    </main>
    <ShareBox client:visible url={shareURL} />
  </div>
  <script define:vars={{ rawMarkdown }}>
    window.__RAW_MD__ = rawMarkdown;
  </script>
  <script is:inline>
    function initAltBadges() {
      var containers = document.querySelectorAll('.content-white-inner');
      for (var i = 0; i < containers.length; i++) {
        var images = containers[i].querySelectorAll('img');
        for (var j = 0; j < images.length; j++) {
          var img = images[j];
          var alt = img.getAttribute('alt');
          if (!alt || alt.trim() === '') continue;
          if (img.closest('a[href*="buymeacoffee"]')) continue;
          if (img.parentElement && img.parentElement.classList.contains('alt-badge-figure')) continue;
 
          var figure = document.createElement('figure');
          figure.className = 'alt-badge-figure';
          img.parentNode.insertBefore(figure, img);
          figure.appendChild(img);
 
          var btn = document.createElement('button');
          btn.className = 'alt-badge-btn';
          btn.type = 'button';
          btn.setAttribute('aria-label', '画像の説明テキストを表示');
          btn.textContent = 'ALT';
          figure.appendChild(btn);
 
          var dialog = document.createElement('dialog');
          dialog.className = 'alt-badge-dialog';
          var textP = document.createElement('p');
          textP.className = 'alt-badge-dialog__text';
          textP.textContent = alt;
          dialog.appendChild(textP);
          var form = document.createElement('form');
          form.method = 'dialog';
          var closeBtn = document.createElement('button');
          closeBtn.type = 'submit';
          closeBtn.className = 'alt-badge-dialog__close';
          closeBtn.textContent = '閉じる';
          form.appendChild(closeBtn);
          dialog.appendChild(form);
          figure.appendChild(dialog);
        }
      }
    }
 
    // Event delegation for ALT badge clicks
    document.addEventListener('click', function(e) {
      var btn = e.target.closest('.alt-badge-btn');
      if (btn) {
        e.preventDefault();
        e.stopPropagation();
        var dialog = btn.parentElement.querySelector('.alt-badge-dialog');
        if (dialog) {
          dialog.showModal();
        }
        return;
      }
    });
 
    // Run badge creation after content is rendered
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initAltBadges);
    } else {
      initAltBadges();
    }
    setTimeout(initAltBadges, 2000);
  </script>
  <script is:inline>
    // ===== Content Image Lightbox =====
    function openLightbox(imgSrc, imgAlt) {
      var existing = document.querySelector('.content-lightbox');
      if (existing) existing.remove();
 
      var overlay = document.createElement('div');
      overlay.className = 'content-lightbox';
      overlay.setAttribute('role', 'dialog');
      overlay.setAttribute('aria-label', '画像プレビュー');
 
      var inner = document.createElement('div');
      inner.className = 'content-lightbox-inner';
 
      var closeBtn = document.createElement('button');
      closeBtn.className = 'content-lightbox-close';
      closeBtn.setAttribute('aria-label', '閉じる');
      closeBtn.textContent = '\u00d7';
      closeBtn.addEventListener('click', function() { closeLightbox(); });
 
      var img = document.createElement('img');
      img.src = imgSrc;
      img.alt = imgAlt || '';
      img.addEventListener('click', function() { closeLightbox(); });
 
      inner.appendChild(closeBtn);
      inner.appendChild(img);
      overlay.appendChild(inner);
      document.body.appendChild(overlay);
 
      // Prevent background scroll
      document.body.style.overflow = 'hidden';
 
      // Fade in
      requestAnimationFrame(function() {
        overlay.classList.add('content-lightbox--visible');
      });
 
      // Close on overlay click (not on inner content)
      overlay.addEventListener('click', function(e) {
        if (e.target === overlay) closeLightbox();
      });
    }
 
    function closeLightbox() {
      var overlay = document.querySelector('.content-lightbox');
      if (!overlay) return;
      overlay.classList.remove('content-lightbox--visible');
      setTimeout(function() {
        overlay.remove();
        document.body.style.overflow = '';
      }, 200);
    }
 
    // ESC key to close
    document.addEventListener('keydown', function(e) {
      if (e.key === 'Escape') closeLightbox();
    });
 
    // Delegate click on content images
    document.addEventListener('click', function(e) {
      var img = e.target.closest('.content-white-inner img');
      if (!img) return;
      // Skip non-content images (buymeacoffee etc.)
      if (img.closest('a[href*="buymeacoffee"]')) return;
      // Skip ALT badge buttons
      if (e.target.closest('.alt-badge-btn')) return;
 
      e.preventDefault();
      e.stopPropagation();
 
      // Use the original (non-resized) image for high quality
      var src = img.getAttribute('src') || '';
      src = src.replace(/-640(\.\w+)$/, '$1');
      openLightbox(src, img.getAttribute('alt'));
    });
  </script>
</Layout>